package com.dx.architectureddd.common.dp.rule;

import lombok.Data;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * 业务执行逻辑组装器
 *
 * @author xin.deng
 * @date 2023/09/24
 */
public class RuleBuilder<T> {
    private volatile Integer isPair = 0;
    private volatile RulePair rulePair;
    private final List<RulePair> list;

    public RuleBuilder() {
        this.list = new ArrayList<>();
    }

    public RuleBuilder<T> when(final Predicate<T> condition) {
        if (isPair != 0) {
            throw new RuntimeException("expect then,not when");
        }
        rulePair = new RulePair();
        rulePair.setCondition(condition);
        isPair++;
        return this;
    }

    public RuleBuilder<T> then(final Consumer<T> action) {
        if (isPair != 1) {
            throw new RuntimeException("expect when,not then");
        }
        isPair--;
        rulePair.setAction(action);
        this.list.add(rulePair);
        return this;
    }

    public Rule<T> createRule() {
        return new DefaultRule<>(this.list);
    }

    @Data
    class RulePair {
        private Predicate condition;
        private Consumer action;
    }
}
